"""
CREAT: 2017/10/15
AUTHOR:　HEHAHUTU
"""
from login.models import Token
from django.http.response import JsonResponse
from datetime import datetime
import pytz


# 装饰器验证token是否可用
def check_token(func):
    def wrapper(request):
        token = request.COOKIES.get('token')
        print(f'check: {token}')
        if token:
            check = Token.objects.filter(token_key__exact=token)
            if check:
                pz = pytz.timezone('Asia/Shanghai')
                check_expire = datetime.now(pz) - check[0].expire_date
                print(check_expire)
                if check_expire.days > 0:
                    check[0].delete()
                    return JsonResponse({'status': 'Exception', 'msg': 'auth token expire date'})
                else:
                    return func(request)
            else:
                return JsonResponse({'status': 'Exception', 'msg': 'auth token error'})
        else:
            return JsonResponse({'status': 'Exception', 'msg': 'auth token null'})

    return wrapper


def check_login_token(func):
    def wrapper(request):
        token = request.COOKIES.get('token')
        print(f'check: {token}')
        if token:
            check = Token.objects.filter(token_key__exact=token)
            if check:
                pz = pytz.timezone('Asia/Shanghai')
                check_expire = datetime.now(pz) - check[0].expire_date
                print(check_expire)
                if check_expire.days > 0:
                    check[0].delete()
                    return func(request)
                else:
                    return JsonResponse({'status': 'ok', 'token': token, 'msg': 'repeat login'})
            else:
                return func(request)
        else:
            return func(request)

    return wrapper
